package com.hr.异步调用;

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: leetcode
 * @description: 哲学家 死锁
 * @author: HuRan QQ1345122890
 * @create: 2021-08-17 10:19
 */
public class DeadLockTest {

    public static void main(String[] args) {
        ChopStick c1 = new ChopStick("1");
        ChopStick c2 = new ChopStick("2");
        ChopStick c3 = new ChopStick("3");
        ChopStick c4 = new ChopStick("4");
        ChopStick c5 = new ChopStick("5");
        new Philoshper("苏格拉底", c1, c2).start();
        new Philoshper("泼辣图", c2, c3).start();
        new Philoshper("亚里士多德", c3, c4).start();
        new Philoshper("赫拉克里特", c4, c5).start();
        new Philoshper("阿基米德", c5, c1).start();


    }
}

class Philoshper extends Thread {
    private String name;
    ChopStick left;
    ChopStick right;

    public Philoshper(String name, ChopStick left, ChopStick right) {
        this.name = name;
        this.left = left;
        this.right = right;
    }

    @SneakyThrows
    @Override
    public void run() {
        while (true) {
            if (left.tryLock()) {
                try {
                    if (right.tryLock()) {

                        try {
                            eat();
                        } finally {
                            right.unlock();
                        }
                    }
                } finally {
                    left.unlock();
                }
            }
        }
    }

    private void eat() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(100);
        System.out.println(name + "  eating");
    }
}

class ChopStick extends ReentrantLock {
    String name;

    public ChopStick(String name) {
        this.name = name;
    }
}